package com.family.pedigree.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.family.pedigree.domain.FamilyArticle;
import com.family.pedigree.domain.FamilyLeader;
import com.family.pedigree.domain.FamilyTreeBrief;
import com.family.pedigree.domain.FamilyTreeNode;
import com.family.pedigree.domain.common.*;
import com.family.pedigree.domain.dto.FamilyStatisticsDto;
import com.family.pedigree.service.*;
import com.family.system.service.IFamilyTreeBriefService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author forever
 * Date 2025/1/14 0:01
 */
@Service
@RequiredArgsConstructor
public class FamilyStatisticsServiceImpl implements IFamilyStatisticsService {

    private final IFamilyArticleService familyArticleService;

    private final IFamilyTreeBriefService familyTreeBriefService;

    private final IFamilyTreeNodeService nodeService;

    private final IFamilyLeaderService familyLeaderService;

    private final IFamilyUserIncomeService incomeService;

    private final IFamilyUserInsuranceService insuranceService;

    private final IFamilyCompanyService familyCompanyService;

    @Override
    public FamilyStatisticsDto panel() {
        FamilyStatisticsDto result = new FamilyStatisticsDto();

        //公告
        FamilyArticle notice = familyArticleService.getNotice();

        //村庄9大模块
        List<?> list = familyTreeBriefService.getList(null);

        //总入家谱人数
        long familyCount = nodeService.count(Wrappers.<FamilyTreeNode>lambdaQuery().eq(FamilyTreeNode::getIsDelete, 'Y'));

        //往任领导
        List<FamilyLeader> noNowLeaders = familyLeaderService.getLeaderByNow(1);
        //现任领导
        List<FamilyLeader> leaderByNow = familyLeaderService.getLeaderByNow(0);

        //年龄比例查询
        List<FamilyAgeClass> familyAges = nodeService.findAgeClass();

        //产业类型
        List<KeyValues> companyIndustry = familyCompanyService.findTypeAmount();
        //企业资产
        List<KeyValues> companyAmount = familyCompanyService.findAmountByYear();
        //村民平均收入
        List<KeyValues> avgIncome = incomeService.findAvgIncome();
        //保险覆盖率
        List<KeyValues> avgInsurance = insuranceService.findInsuranceByYear();
        //学历统计
        List<FamilyCollage> collages = nodeService.findCollage();

        //省份人口统计
        List<ProvinceNum> provinceCount = nodeService.findProvinceCount();

        result.setNotice(notice);
        result.setFamilyBriefs((List<FamilyTreeBrief>) list);
        result.setFamilyCount(familyCount);
        result.setOldFamilyLeaders(noNowLeaders);
        result.setNowFamilyLeaders(leaderByNow);
        result.setFamilyAges(familyAges);
        result.setCompanyIndustry(companyIndustry);
        result.setAverageRevenue(avgIncome);
        result.setInsurances(avgInsurance);
        result.setCompanyAnnualAssets(companyAmount);
        result.setEducations(collages);
        result.setProvinceCount(provinceCount);

        //统计男女比例 todo:待完成
        List<FamilyTreeNode> allPeople = nodeService.list();

// 按出生年份分组统计
        Map<Integer, FamilyMan> statsByYear = allPeople.stream()
                .filter(person -> person.getGender() != null && person.getBirthday() != null)
                .collect(Collectors.groupingBy(
                        person -> person.getBirthday().getYear(),
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list1 -> {
                                    long maleCount = list1.stream()
                                            .filter(p -> "男".equals(p.getGender()) || "male".equalsIgnoreCase(p.getGender()))
                                            .count();
                                    long femaleCount = list1.size() - maleCount;

                                    // 确保使用正确的构造函数或setter方法
                                    return new FamilyMan()
                                            .setTotal(list1.size())
                                            .setMan((int) maleCount)
                                            .setWoman((int) femaleCount);
                                }
                        )
                ));

// 转换为列表并排序
        List<FamilyMan> resultList = statsByYear.entrySet().stream()
                .map(entry -> {
                    FamilyMan fm = entry.getValue();
                    return fm.setYear(String.valueOf(entry.getKey())); // 设置年份
                })
                .sorted(Comparator.comparing(FamilyMan::getYear).reversed())
                .collect(Collectors.toList());

        result.setFamilyMens(resultList);

        return result;
    }
}
